"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : postgres_fdw
Case Name   : 含Windows函数下推失败
Create At   : 2023-01-05
Owner       : opentestcase004
Description :
    1.安装postgres_fdw扩展,创建外部服务器,用户映射,模式
    2.建基表
    3.创建外表
    4.向外表插入数据
    5.explain观察含Windows函数的下推是否成功
    6.清理环境
Expect      :
    1.成功
    2.成功
    3.成功
    4.成功
    5.下推失败,执行计划打印所有窗口函数操作在本地执行
    6.成功
History     : 
"""

import os
import unittest
from yat.test import Node
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class PostgresFdw(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info("-----------this is setup-----------")
        self.log.info(f"-----{os.path.basename(__file__)} start-----")
        self.constant = Constant()
        self.pri_userdb = Node(node='PrimaryDbUser')
        self.commsh = CommonSH('PrimaryDbUser')
        self.tb_name1 = 't_postgres_fdw_foreign_0026_01'
        self.tb_name2 = 't_postgres_fdw_foreign_0026_02'
        self.server = 'se_postgres_fdw_foreign_0026'
        self.schema = 's_postgres_fdw_foreign_0026'
        self.port = self.pri_userdb.db_port
        self.database = self.pri_userdb.db_name

    def test_pub_sub(self):
        text = "--step1:安装postgres_fdw扩展,创建外部服务器,用户映射,模式" \
               "expect:成功--"
        self.log.info(text)
        sql_cmd = f"drop extension if exists postgres_fdw cascade;" \
            f"create extension if not exists postgres_fdw;"
        result = self.commsh.execut_db_sql(sql_cmd)
        self.log.info(result)
        self.assertIn(self.constant.drop_extension_success, result,
                      '执行失败' + text)
        self.assertIn(self.constant.create_extension_success, result,
                      '执行失败' + text)

        sql_cmd = f"drop server if exists {self.server} cascade;" \
            f"create server {self.server} foreign data wrapper postgres_fdw " \
            f"options (dbname '{self.database}', port '{self.port}');"
        result = self.commsh.execut_db_sql(sql_cmd)
        self.log.info(result)
        self.assertIn(self.constant.drop_server_success, result,
                      '执行失败' + text)
        self.assertIn(self.constant.create_server_success, result,
                      '执行失败' + text)

        sql_cmd = f"drop user mapping if exists for current_user server " \
            f"{self.server};create user mapping for current_user server " \
            f"{self.server};"
        result = self.commsh.execut_db_sql(sql_cmd)
        self.log.info(result)
        self.assertIn(self.constant.drop_usermapping_success, result,
                      '执行失败' + text)
        self.assertIn(self.constant.create_usermapping_success, result,
                      '执行失败' + text)

        sql_cmd = f"drop schema if exists {self.schema} cascade;" \
            f"create schema {self.schema};"
        result = self.commsh.execut_db_sql(sql_cmd)
        self.log.info(result)
        self.assertIn(self.constant.DROP_SCHEMA_SUCCESS_MSG, result,
                      '执行失败' + text)
        self.assertIn(self.constant.CREATE_SCHEMA_SUCCESS_MSG, result,
                      '执行失败' + text)

        text = "--step2:建基表 expect:成功--"
        self.log.info(text)
        sql_cmd = f"drop table if exists {self.schema}.{self.tb_name1};" \
            f"create table {self.schema}.{self.tb_name1}(col_1 int, col_2 " \
            f"date, col_3 char(5));"
        result = self.commsh.execut_db_sql(sql_cmd)
        self.log.info(result)
        self.assertIn(self.constant.DROP_TABLE_SUCCESS, result, '执行失败' +
                      text)
        self.assertIn(self.constant.TABLE_CREATE_SUCCESS, result, '执行失败' +
                      text)

        text = "--step3:创建外表 expect:成功--"
        self.log.info(text)
        sql_cmd = f"drop foreign table if exists {self.tb_name2};" \
            f"create foreign table {self.tb_name2} (col_1 int, col_2 date," \
            f" col_3 char(5)) server {self.server} options (schema_name " \
            f"'{self.schema}', table_name '{self.tb_name1}');"
        result = self.commsh.execut_db_sql(sql_cmd)
        self.log.info(result)
        self.assertIn(self.constant.DROP_FOREIGN_SUCCESS_MSG, result,
                      '执行失败' + text)
        self.assertIn(self.constant.CREATE_FOREIGN_SUCCESS_MSG, result,
                      '执行失败' + text)

        text = "--step4:向外表插入数据 expect:成功--"
        self.log.info(text)
        sql_cmd = f"insert into {self.tb_name2} values(" \
            f"generate_series(1,100000), generate_series(" \
            f"'2022-11-29 10:01:01'::timestamp, '2022-11-30 18:01:01'" \
            f"::timestamp, interval '1 day'), 'a');" \
            f"analyse {self.tb_name2};"
        result = self.commsh.execut_db_sql(sql_cmd)
        self.log.info(result)
        self.assertIn(self.constant.INSERT_SUCCESS_MSG, result, '执行失败' +
                      text)
        self.assertIn(self.constant.ANALYZE_SUCCESS_MSG, result, '执行失败' +
                      text)

        text = "--step5:explain观察含窗口函数的下推是否成功 expect:" \
               "下推失败,执行计划打印所有窗口函数操作在本地执行--"
        self.log.info(text)
        sql_cmd = f"explain (verbose,analyse) select col_1,col_2,col_3,rank()" \
            f" over(partition by col_1 order by col_2) from {self.tb_name2};"
        result = self.commsh.execut_db_sql(sql_cmd)
        self.log.info(result)
        result_split = result.splitlines()
        result_split1 = str(result_split[2]).strip()
        result_split2 = str(result_split[-3]).strip()
        self.assertIn('WindowAgg', result_split1, '执行失败' + text)
        self.assertEqual(f'Remote SQL: SELECT col_1, col_2, col_3 FROM '
                         f'{self.schema}.{self.tb_name1} ORDER BY col_1 ASC '
                         f'NULLS LAST, col_2 ASC NULLS LAST', result_split2,
                         '执行失败' + text)
        sql_cmd = f"explain (verbose,analyse) select col_1,col_2,col_3,row_" \
            f"number() over(partition by col_1 order by col_2) from " \
            f"{self.tb_name2} where col_1 >10;"
        result = self.commsh.execut_db_sql(sql_cmd)
        self.log.info(result)
        result_split = result.splitlines()
        result_split1 = str(result_split[2]).strip()
        result_split2 = str(result_split[-3]).strip()
        self.assertIn('WindowAgg', result_split1, '执行失败' + text)
        self.assertEqual(f'Remote SQL: SELECT col_1, col_2, col_3 FROM '
                         f'{self.schema}.{self.tb_name1} WHERE ((col_1 > 10))'
                         f' ORDER BY col_1 ASC NULLS LAST, col_2 ASC NULLS '
                         f'LAST', result_split2, '执行失败' + text)
        sql_cmd = f"explain (verbose,analyse) select col_1,col_2,col_3," \
            f"dense_rank() over(partition by col_1 order by col_2) from " \
            f"{self.tb_name2} order by col_1;"
        result = self.commsh.execut_db_sql(sql_cmd)
        self.log.info(result)
        result_split = result.splitlines()
        result_split1 = str(result_split[2]).strip()
        result_split2 = str(result_split[-3]).strip()
        self.assertIn('WindowAgg', result_split1, '执行失败' + text)
        self.assertEqual(f'Remote SQL: SELECT col_1, col_2, col_3 FROM '
                         f'{self.schema}.{self.tb_name1} ORDER BY col_1 ASC'
                         f' NULLS LAST, col_2 ASC NULLS LAST', result_split2,
                         '执行失败' + text)
        sql_cmd = f"explain (verbose,analyse) select col_1,col_2,col_3," \
            f"percent_rank() over(partition by col_1 order by col_2) from " \
            f"{self.tb_name2} offset 5 limit 0;"
        result = self.commsh.execut_db_sql(sql_cmd)
        self.log.info(result)
        result_split = result.splitlines()
        result_split1 = str(result_split[2]).strip()
        result_split2 = str(result_split[-3]).strip()
        result_split3 = str(result_split[4]).strip()
        self.assertIn('Limit', result_split1, '执行失败' + text)
        self.assertEqual(f'Remote SQL: SELECT col_1, col_2, col_3 FROM '
                         f'{self.schema}.{self.tb_name1} ORDER BY col_1 '
                         f'ASC NULLS LAST, col_2 ASC NULLS LAST',
                         result_split2, '执行失败' + text)
        self.assertIn('WindowAgg', result_split3, '执行失败' + text)
        sql_cmd = f"explain (verbose,analyse) select col_1,col_2,col_3," \
            f"cume_dist() over(partition by col_1 order by col_2) from " \
            f"{self.tb_name2} offset 5 limit 0;"
        result = self.commsh.execut_db_sql(sql_cmd)
        self.log.info(result)
        result_split = result.splitlines()
        result_split1 = str(result_split[2]).strip()
        result_split2 = str(result_split[-3]).strip()
        result_split3 = str(result_split[4]).strip()
        self.assertIn('Limit', result_split1, '执行失败' + text)
        self.assertEqual(f'Remote SQL: SELECT col_1, col_2, col_3 FROM '
                         f'{self.schema}.{self.tb_name1} ORDER BY col_1 ASC '
                         f'NULLS LAST, col_2 ASC NULLS LAST', result_split2,
                         '执行失败' + text)
        self.assertIn('WindowAgg', result_split3, '执行失败' + text)
        sql_cmd = f"explain (verbose,analyse) select col_1,col_2,col_3," \
            f"ntile(3) over(partition by col_1 order by col_2) from " \
            f"{self.tb_name2};"
        result = self.commsh.execut_db_sql(sql_cmd)
        self.log.info(result)
        result_split = result.splitlines()
        result_split1 = str(result_split[2]).strip()
        result_split2 = str(result_split[-3]).strip()
        self.assertIn('WindowAgg', result_split1, '执行失败' + text)
        self.assertEqual(f'Remote SQL: SELECT col_1, col_2, col_3 FROM '
                         f'{self.schema}.{self.tb_name1} ORDER BY col_1 ASC '
                         f'NULLS LAST, col_2 ASC NULLS LAST', result_split2,
                         '执行失败' + text)
        sql_cmd = f"explain (verbose,analyse) select col_1,col_2,col_3," \
            f"lag(col_1,3,1) over(partition by col_1 order by col_2) from" \
            f" {self.tb_name2};"
        result = self.commsh.execut_db_sql(sql_cmd)
        self.log.info(result)
        result_split = result.splitlines()
        result_split1 = str(result_split[2]).strip()
        result_split2 = str(result_split[-3]).strip()
        self.assertIn('WindowAgg', result_split1, '执行失败' + text)
        self.assertEqual(f'Remote SQL: SELECT col_1, col_2, col_3 FROM '
                         f'{self.schema}.{self.tb_name1} ORDER BY col_1 ASC '
                         f'NULLS LAST, col_2 ASC NULLS LAST', result_split2,
                         '执行失败' + text)
        sql_cmd = f"explain (verbose,analyse) select col_1,col_2,col_3," \
            f"lead(col_1,2,1) over(partition by col_2 order by col_1) from " \
            f"{self.tb_name2};"
        result = self.commsh.execut_db_sql(sql_cmd)
        self.log.info(result)
        result_split = result.splitlines()
        result_split1 = str(result_split[2]).strip()
        result_split2 = str(result_split[-3]).strip()
        self.assertIn('WindowAgg', result_split1, '执行失败' + text)
        self.assertEqual(f'Remote SQL: SELECT col_1, col_2, col_3 FROM '
                         f'{self.schema}.{self.tb_name1} ORDER BY col_2 ASC '
                         f'NULLS LAST, col_1 ASC NULLS LAST', result_split2,
                         '执行失败' + text)
        sql_cmd = f"explain (verbose,analyse) select col_1,col_2,col_3," \
            f"first_value(col_1) over(partition by col_2 order by col_1) from" \
            f" {self.tb_name2};"
        result = self.commsh.execut_db_sql(sql_cmd)
        self.log.info(result)
        result_split = result.splitlines()
        result_split1 = str(result_split[2]).strip()
        result_split2 = str(result_split[-3]).strip()
        self.assertIn('WindowAgg', result_split1, '执行失败' + text)
        self.assertEqual(f'Remote SQL: SELECT col_1, col_2, col_3 FROM '
                         f'{self.schema}.{self.tb_name1} ORDER BY col_2 ASC '
                         f'NULLS LAST, col_1 ASC NULLS LAST', result_split2,
                         '执行失败' + text)
        sql_cmd = f"explain (verbose,analyse) select col_1,col_2,col_3," \
            f"last_value(col_2) over(partition by col_2 order by col_1) from" \
            f" {self.tb_name2};"
        result = self.commsh.execut_db_sql(sql_cmd)
        self.log.info(result)
        result_split = result.splitlines()
        result_split1 = str(result_split[2]).strip()
        result_split2 = str(result_split[-3]).strip()
        self.assertIn('WindowAgg', result_split1, '执行失败' + text)
        self.assertEqual(f'Remote SQL: SELECT col_1, col_2, col_3 FROM '
                         f'{self.schema}.{self.tb_name1} ORDER BY col_2 ASC '
                         f'NULLS LAST, col_1 ASC NULLS LAST', result_split2,
                         '执行失败' + text)
        sql_cmd = f"explain (verbose,analyse) select col_1,col_2,col_3,nth_" \
            f"value(col_1,4) over(partition by col_2 order by col_1) from" \
            f" {self.tb_name2};"
        result = self.commsh.execut_db_sql(sql_cmd)
        self.log.info(result)
        result_split = result.splitlines()
        result_split1 = str(result_split[2]).strip()
        result_split2 = str(result_split[-3]).strip()
        self.assertIn('WindowAgg', result_split1, '执行失败' + text)
        self.assertEqual(f'Remote SQL: SELECT col_1, col_2, col_3 FROM '
                         f'{self.schema}.{self.tb_name1} ORDER BY col_2 ASC '
                         f'NULLS LAST, col_1 ASC NULLS LAST', result_split2,
                         '执行失败' + text)

    def tearDown(self):
        text = "--step6:清理环境 expect:成功--"
        self.log.info(text)
        sql_cmd = f"drop extension if exists postgres_fdw cascade; " \
            f"drop server if exists {self.server} cascade;" \
            f"drop user mapping if exists for current_user server " \
            f"{self.server};drop schema if exists {self.schema} cascade;" \
            f"drop foreign table if exists {self.tb_name2};"
        result = self.commsh.execut_db_sql(sql_cmd)
        self.log.info(result)
        self.assertIn(self.constant.drop_extension_success, result,
                      '执行失败' + text)
        self.assertIn(self.constant.drop_server_success, result,
                      '执行失败' + text)
        self.assertIn(self.constant.drop_usermapping_success, result,
                      '执行失败' + text)
        self.assertIn(self.constant.DROP_SCHEMA_SUCCESS_MSG, result,
                      '执行失败' + text)
        self.assertIn(self.constant.DROP_FOREIGN_SUCCESS_MSG, result,
                      '执行失败' + text)
        self.log.info(f"-----{os.path.basename(__file__)} end-----")
